﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Linq;
using System.Net;
using MySQL.Db;
using MySql.Data.MySqlClient;

namespace Gollie.Ajax
{
	public class CompanyInfo : AjaxResult
	{
		public string Name;
		public string Street;
		public string ZipCode;
		public string City;
		public string KvK;
		public string FailedMsg;

		public CompanyInfo() : base(null) { }

		public CompanyInfo(AjaxArg arg)
			: base(arg)
		{

		}

		protected override void Init(AjaxArg ajaxArg)
		{
			KvK = ajaxArg.token.Trim();

			try
			{
				if (Database.Queries.KvKExists(KvK))
					throw new Exception("Dit kvk nummer is al bekend bij Gollie");

				this.GetValues();
			}
			catch (KeyNotFoundException)
			{
				FailedMsg = "Het KvK-nummer geeft geen geldig resultaat. Probeer het opnieuw, of vul de gegevens met de hand in. Wij zullen ze dan later verifiëren.";
			}
			catch (WebException e)
			{
				FailedMsg = "Het is op dit moment niet mogelijk om uw bedrijfsgegevens op te halen. U kunt het later nog eens proberen of ze met de hand in invullen. De fout is: " + e.Message;
			}
			catch (MySqlException mySqlEx)
			{
				this.ErrorCode = mySqlEx.Number;
				this.ErrorMessage = MySqlErrorCodes.GetInstance().GetMessage(mySqlEx);
				logger.Warn("SQL Error in CompanyInfo {0}", this.ErrorMessage);
			}
			catch (Exception e)
			{
				if (this.ErrorCode == 0)
					this.ErrorCode = 99;

				this.ErrorMessage = e.Message;
				logger.Warn("Error in CompanyInfo {0}", this.ErrorMessage);
			}
		}

		private void GetValues()
		{
			Name = ""; Street = ""; ZipCode = ""; City = ""; FailedMsg = "";
			try
			{
				XDocument xdoc = XDocument.Load(ConfigAppSettings.GetValue("KvkUrl") + KvK);

				XElement root = xdoc.Element("rechtspersonen");
				if (root == null)
					throw new WebException("No response.");

				Name = GetKvKValue(root, "bedrijfsnaam");
				Street = GetKvKValue(root, "adres");
				ZipCode = GetKvKValue(root, "postcode");
				City = GetKvKValue(root, "woonplaats");
			}
			catch (WebException we)
			{
				bool notFound = (we.Status == System.Net.WebExceptionStatus.ProtocolError
									&& we.Response is HttpWebResponse
									&& ((HttpWebResponse)we.Response).StatusCode == HttpStatusCode.NotFound);
				if (notFound)
					throw new KeyNotFoundException();
				else
					throw;
			}
			catch (Exception ex)
			{
				throw new WebException(ex.Message);
			}
		}

		private string GetKvKValue(XElement root, string nodeName)
		{
			IEnumerable<XElement> elts = root.Descendants(nodeName);
			if (elts.Count() > 0)
			{
				XElement elt = elts.First();
				if (elt != null)
					return elt.Value;
			}

			return "";
		}
	}
}